/**
 * 
 */
package cn.falcon.fmobi.console.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.stereotype.Component;

/**
 * api权限过滤器
 * @author Administrator
 */
@Component
public class APIPermissionsAuthorizationFilter extends AuthorizationFilter {


	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		if(subject == null || !subject.isAuthenticated()){
			return false;
		}
		// 可以加入详细权限判断
		return true;
	}


	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		//此处可以加入详细返回结果
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(buildErrorResult(20001, "访问口令或者会话已失效", null));
		response.getWriter().flush();
		response.getWriter().close();
		return false;
	}
	
	/**
	 * 创建错误返回结果
	 * @return
	 */
	private String buildErrorResult(int errCode, String message, String exception){
		StringBuilder sb = new StringBuilder();
		sb.append("{")
		  .append("\"ret\" : ")
		  .append(errCode).append(",")
		  .append("\"err_msg\" :")
		  .append("\"")
		  .append(message).append("\"").append(",")
		  .append("\"exception\" :")
		  .append("\"\"")
		  .append("}");
	   return sb.toString();
	}
}
